package com.peanut.baby.mvp.login;

import android.app.Activity;

import com.peanut.baby.InitManager;
import com.peanut.baby.http.BaseObserver;
import com.peanut.baby.http.BaseResponse;
import com.peanut.baby.http.BaseScheduler;
import com.peanut.baby.http.RetrofitClient;
import com.peanut.baby.model.AuthrizeInfo;
import com.peanut.baby.model.User;
import com.peanut.devlibrary.util.DeviceInfo;
import com.peanut.devlibrary.util.SmsUtil;
import com.peanut.devlibrary.util.StringUtil;
import com.tencent.mars.xlog.Log;

import java.util.HashMap;

import cn.nekocode.rxlifecycle.RxLifecycle;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import io.reactivex.Observable;

/**
 * Created by anonymouslystudio on 2017/7/5.
 */

public class LoginPresenter implements LoginContract.Presenter,SmsUtil.OnSmsStatusChangeListener{
    private static final String TAG = LoginPresenter.class.getSimpleName();
    private PlatformLoginListener listener;
    private Runnable countRunnable;
    private Thread  countThread;
    protected LoginContract.View view;
    private Activity    activity;
    public LoginPresenter(LoginContract.View view,Activity activity){
        this.view = view;
        this.activity = activity;
    }

    @Override
    public void getVCode(String mobile) {
        Log.d(TAG,"getCode: "+mobile);
        SmsUtil.getInstance().setOnSmsStatusChangeListener(this);
        SmsUtil.getInstance().registReceiver();
        SmsUtil.getInstance().getVCode(mobile);
    }

    @Override
    public void submitSdkLogin(final AuthrizeInfo info) {
        Log.d(TAG,"submitSdkLogin");
        Observable observable = RetrofitClient.getInstance().sdkLogin(info.openId,
                info.accessToken,
                info.expireIn+"",
                info.type+"",
                info.uuid,
                info.idfa,
                info.mac,
                info.ipAddress,
                info.device,
                info.osversion,
                info.model,
                info.version,
                info.screen,
                info.network,
                System.currentTimeMillis()+"",
                info.nickname,
                info.avatar,
                info.gender,
                info.province,
                info.city,
                info.country,
                info.unionid);
        observable.compose(BaseScheduler.<BaseResponse<User>>compose())
                .compose(RxLifecycle.bind(activity).withObservable()).subscribe(new BaseObserver<User>() {
            @Override
            protected void onHandleSuccess(User o) {
                o.openid = info.openId;
                InitManager.getInstance().setUser(o);
                view.onLoginSuccess();
            }

            @Override
            protected void onHandleError(String code,String msg) {
                view.onFailed(msg);
            }

        });
    }

    @Override
    public void wxAuth() {
        Platform platform = ShareSDK.getPlatform(Wechat.NAME);
        if(platform != null){
            if(platform.isAuthValid()){
                platform.removeAccount(true);
            }
            if(listener == null){
                listener = new PlatformLoginListener();
            }
            Log.d(TAG,"listener == null? "+(listener == null));
            platform.setPlatformActionListener(listener);
            platform.showUser(null);
        }
    }

    /**
     * call when get code request success
     */
    private void startCountDown(){
        stopThreadAndRunnable();
        countRunnable = new CountingRunnable();
        countThread = new Thread(countRunnable);
        countThread.start();
    }

    private void stopThreadAndRunnable(){

        try {
            if(countThread != null){
//                countThread.stop();
            }
            countThread = null;
            if(countRunnable != null){
                countRunnable = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            countThread = null;
            countRunnable = null;
        }
    }

    @Override
    public void onRequestSmsFinished(boolean success, String failReason) {
        Log.d(TAG,"onRequestSmsFinished success? "+success+" failReason: "+failReason);
        if(success){
            startCountDown();
        }else{
            view.onFailed("请求验证码失败 "+failReason);
        }

    }

    /**
     *
     */
    public void submitLoginRequest(String mobile,String code){
        Log.d(TAG,"submitLoginRequest");
        Observable observable = RetrofitClient.getInstance().login(mobile,code);
        observable.compose(BaseScheduler.<BaseResponse<User>>compose())
                .compose(RxLifecycle.bind(activity).withObservable())
                .subscribe(new BaseObserver<User>() {
            @Override
            protected void onHandleSuccess(User o) {
                InitManager.getInstance().setUser(o);
                view.onLoginSuccess();
            }

            @Override
            protected void onHandleError(String code,String msg) {
                view.onFailed(msg);
            }

        });
    }

    public void testLogin(String mobile){
        Log.d(TAG,"testLogin");
        Observable observable = RetrofitClient.getInstance().testLogin(mobile);
        observable.compose(BaseScheduler.<BaseResponse<User>>compose())
                .compose(RxLifecycle.bind(activity).withObservable())
                .subscribe(new BaseObserver<User>() {
            @Override
            protected void onHandleSuccess(User o) {
                InitManager.getInstance().setUser(o);
                view.onLoginSuccess();
            }

            @Override
            protected void onHandleError(String code,String msg) {
                view.onFailed(msg);
            }

        });
    }


    class PlatformLoginListener implements PlatformActionListener {

        @Override
        public void onComplete(Platform platform, int i, HashMap<String, Object> res) {
            //解析部分用户资料字段
            Log.d(TAG,"onComplete: "+i+" "+platform.getName()) ;

            Log.d(TAG,"ACTION_USER_INFOR");

                PlatformDb platDB = platform.getDb();//获取数平台数据DB
                Log.d(TAG,"platDB is null "+(platDB == null)+" isValid  "+platDB.isValid());
                final AuthrizeInfo info;

                if(platDB != null && platDB.isValid()) {
                    info = new AuthrizeInfo();
                    info.accessToken = platDB.getToken();
                    info.expireIn = platDB.getExpiresTime();
                    info.openId = platDB.getUserId();


                    info.type = AuthrizeInfo.TYPE_WEIXIN;
                    info.unionid = res.get("unionid").toString();

                    if (res.containsKey("headimgurl")) {
                        info.avatar = res.get("headimgurl").toString();
                    }

                    if (res.containsKey("nickname")) {
                        info.nickname = res.get("nickname").toString();
                    }

                    if (res.containsKey("country")) {
                        info.country = res.get("country").toString();
                    }

                    if (res.containsKey("city")) {
                        info.city = res.get("city").toString();
                    }

                    if (res.containsKey("province")) {
                        info.province = res.get("province").toString();
                    }
                    info.gender = platDB.getUserGender();
                    if(StringUtil.isNullOrEmpty(info.gender)){
                        info.gender = User.GENDER_MALE;
                    }else{
                        if(info.gender.equals("0") || info.gender.equals("m")){
                            info.gender = User.GENDER_MALE;
                        }else{
                            info.gender = User.GENDER_FEMALE;
                        }
                    }

                    Log.d(TAG, "A" + info.toString());

                    info.uuid = InitManager.getInstance().info.uuid;
                    info.mac = InitManager.getInstance().info.mac;
                    info.ipAddress = InitManager.getInstance().info.ip;
                    info.device = DeviceInfo.device;
                    info.osversion = DeviceInfo.osversion;
                    info.model = DeviceInfo.model;
                    info.version = InitManager.getInstance().info.appversion;
                    info.screen = InitManager.getInstance().info.screen;
                    info.network = InitManager.getInstance().info.network;
                    Log.d(TAG, "onAuthSuccess" + info.toString());
                    view.onAuthSuccess(info);
                }else{
                    Log.d(TAG,"get auth info failed");
                    view.onFailed("无法获取授权信息");
                }
            }

        @Override
        public void onError(Platform platform, int i, Throwable throwable) {
            view.onFailed("授权失败 "+throwable.toString());
        }

        @Override
        public void onCancel(Platform platform, int i) {
            view.onFailed("用户取消授权 ");
        }


    }



    /**
     * 计数器
     */
    class CountingRunnable implements Runnable{
        int current = 60;
        public CountingRunnable() {
        }

        @Override
        public void run() {
            view.startCountDown();
            while(current > 0){
                view.onCountDown(current);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                }
                current --;
            }
            view.onCountComplete();

        }
    }


    public void onDestory(){
        Log.d(TAG,"onDestory");
        stopThreadAndRunnable();

        SmsUtil.getInstance().removeReceiver();
        listener = null;
    }

}
